#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
数据管理模块
负责处理用户号码和开奖数据的存储与读取
"""

import json
import csv
import os
from datetime import datetime

class DataManager:
    """
    数据管理器
    """
    def __init__(self, data_dir=None):
        # 如果未指定数据目录，则使用用户主目录下的路径
        if data_dir is None:
            self.data_dir = os.path.expanduser("~/.local/share/gambling-memories/data")
        else:
            self.data_dir = data_dir
        # 确保数据目录存在
        if not os.path.exists(self.data_dir):
            os.makedirs(self.data_dir)
    
    def save_user_tickets(self, tickets, filename="user_tickets.json"):
        """
        保存用户号码到JSON文件
        """
        filepath = os.path.join(self.data_dir, filename)
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(tickets, f, ensure_ascii=False, indent=2)
        return filepath
    
    def load_user_tickets(self, filename="user_tickets.json"):
        """
        从JSON文件加载用户号码
        """
        filepath = os.path.join(self.data_dir, filename)
        print(f"尝试加载用户票数据文件: {filepath}")
        if not os.path.exists(filepath):
            print("用户票数据文件不存在，返回空列表")
            return []
        
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                data = json.load(f)
                print(f"成功加载用户票数据，共 {len(data)} 条记录")
                return data
        except Exception as e:
            print(f"加载用户票数据时出错: {e}")
            return []

    def save_lottery_history(self, history, filename="lottery_history.json"):
        """
        保存开奖历史到JSON文件
        """
        filepath = os.path.join(self.data_dir, filename)
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(history, f, ensure_ascii=False, indent=2)
        return filepath
    
    def load_lottery_history(self, filename="lottery_history.json"):
        """
        从JSON文件加载开奖历史
        """
        filepath = os.path.join(self.data_dir, filename)
        print(f"尝试加载开奖历史数据文件: {filepath}")
        if not os.path.exists(filepath):
            print("开奖历史数据文件不存在，返回空列表")
            return []
        
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                data = json.load(f)
                print(f"成功加载开奖历史数据，共 {len(data)} 条记录")
                return data
        except Exception as e:
            print(f"加载开奖历史数据时出错: {e}")
            return []

    def add_lottery_result(self, lottery_type, date, numbers, filename="lottery_history.json"):
        """
        添加一条开奖记录
        """
        history = self.load_lottery_history(filename)
        result = {
            "type": lottery_type,
            "date": date,
            "numbers": numbers
        }
        history.append(result)
        self.save_lottery_history(history, filename)
        return result
    
    def get_recent_results(self, lottery_type=None, count=10, filename="lottery_history.json"):
        """
        获取最近的开奖记录
        """
        history = self.load_lottery_history(filename)
        
        # 如果指定了彩票类型，则过滤
        if lottery_type:
            history = [item for item in history if item["type"] == lottery_type]
        
        # 按日期排序并返回最近的记录
        history.sort(key=lambda x: x["date"], reverse=True)
        return history[:count]

# 使用示例和测试代码
if __name__ == "__main__":
    # 创建数据管理器实例
    dm = DataManager()
    
    # 测试保存和加载用户号码
    test_tickets = [
        {
            "type": "double_color_ball",
            "date": "2023-01-01",
            "numbers": [[1, 2, 3, 4, 5, 6], 7]
        },
        {
            "type": "super_lotto",
            "date": "2023-01-01",
            "numbers": [[1, 2, 3, 4, 5], [1, 2]]
        }
    ]
    
    # 保存测试数据
    dm.save_user_tickets(test_tickets)
    print("用户号码已保存")
    
    # 加载测试数据
    loaded_tickets = dm.load_user_tickets()
    print("加载的用户号码:", loaded_tickets)
    
    # 测试保存和加载开奖历史
    test_results = [
        {
            "type": "double_color_ball",
            "date": "2023-01-01",
            "numbers": [[1, 2, 3, 4, 5, 6], 7]
        }
    ]
    
    dm.save_lottery_history(test_results)
    print("开奖历史已保存")
    
    # 添加一条新的开奖记录
    dm.add_lottery_result("double_color_ball", "2023-01-08", [[7, 8, 9, 10, 11, 12], 1])
    print("新开奖记录已添加")
    
    # 获取最近的开奖记录
    recent = dm.get_recent_results()
    print("最近的开奖记录:", recent)